//var taskId = null;
var editIndex = undefined;
var rowCache = {};
var objs = {
	envVarDg: $("#envVarDg")
};

$(function(){
	$.parser.parse();
	var currTaksId = $("#taksIdmain").val();
//	if(currTaksId!='null'&&currTaksId!=''){
//		taskId = currTaksId;
//		loadEnvVar();
//		var rows = objs.envVarDg.xdatagrid('getRows');
//		rowCache['lastIndex'] = rows.length - 1;
//	}
	loadEnvVar();
	var rows = objs.envVarDg.xdatagrid('getRows');
	rowCache['lastIndex'] = rows.length - 1;
});

// 加载环境变量数据
function loadEnvVar() {
	objs.envVarDg.xdatagrid({
		url: baseUrl + '/apiManager/envVarAction!page.action',
		method: 'get',
		queryParams: {'dto.apiEnvVar.taskId':taskId, 'dto.apiEnvVar.type': 1, 'dto.pageSize':100},
//		height: mainObjs.tableHeight - 40,
//		iconCls: 'icon-edit',
		singleSelect: true,
		fitColumns: true,
		resizeHandle: 'right',
		emptyMsg: '暂无数据',
//		toolbar: '#tb',
//		pagination: false,
//		pageNumber: 1,
//		pageSize: 100,
//		layout:['list','first','prev','manual', "sep",'next','last','refresh','info'],
//		pageList: [10,30,50,100],
//		showPageList:true,
		columns:[[
		    {field:'envId',hidden:true},
			{field:'varName',title:'变量名',width:'35%',align:'center',editor: {type:'textbox',options:{prompt:'请输入变量名',onChange:onTextChange}}},
			{field:'varValue',title:'变量值',width:'50%',align:'center',editor: {type:'textbox',options:{prompt:'请输入变量值',onChange:onTextChange}}},
			//{field:'defaultVal',title:'默认',width:'33%',editor: {type:'checkbox',options:{on:'默认值',off:'',onChange:onCheckChange}},formatter:defaultValFormat}
			{field:'operate',title:'操作',width:'15%',align:'center',formatter:operateFormat}
		]],
		onClickCell: onClickCell
	}).xdatagrid('appendRow', {taskId: taskId, status: 1, defaultVal: 0});
}

function defaultValFormat(value,row,index) {
	switch (value) {
//	case 0:
//		return '非默认值';
	case 1:
		return '默认值';
	default:
		return '';
	}
}

function operateFormat(value, row, index) {
	return "<a class='link' href='javascript:void(0);' onclick='delRow("+index+","+row.envId+")'>&times;</a>";
}

//单元格点击事件
function onClickCell(index,field,value) {
	if ('operate' == field) {
		var row = rowCache[editIndex] ? rowCache[editIndex] : objs.envVarDg.xdatagrid('selectRow', index).xdatagrid('getSelected');
		delRow(index, row.envId);
		return;
	}
	if (editIndex != index){
		if (endEditing()){
			objs.envVarDg.xdatagrid('selectRow', index)
				.xdatagrid('beginEdit', index);
			var ed = objs.envVarDg.xdatagrid('getEditor', {index:index,field:field});
			if (ed){
				($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
			}
			editIndex = index;
		} else {
			objs.envVarDg.xdatagrid('selectRow', editIndex);
		}
	}
}

function endEditing(){
	if (editIndex == undefined){return true}
	if (objs.envVarDg.xdatagrid('validateRow', editIndex)){
		objs.envVarDg.xdatagrid('endEdit', editIndex);
		delete rowCache[editIndex];
		editIndex = undefined;
		return true;
	} else {
		return false;
	}
}

//提交保存
function saveEnvVar() {
	var editors = objs.envVarDg.xdatagrid('getEditors', editIndex);
	if (!editors || !editors.length) {
		return;
	}
	
	var row = rowCache[editIndex] ? rowCache[editIndex] : objs.envVarDg.xdatagrid('getSelected');
	var data = {};
	for (const key in row) {
		if (row.hasOwnProperty(key) && row[key]) {
			data['dto.apiEnvVar.'+key] = row[key];
		}
	}
	editors.forEach(function(editor) {
		if ('textbox' == editor.type) {
			data['dto.apiEnvVar.'+editor.field] = $(editor.target)[editor.type]('getValue');
		}
	});
	data['dto.apiEnvVar.type'] = 1;

	var msg = row.envId ? '修改成功' : '保存成功';
	var url = baseUrl + '/apiManager/envVarAction!saveOrUpdate.action';
	$.post(url,data,function(res) {
		if ('success' == res.successFailed) {
			// var rows = objs.envVarDg.xdatagrid('getRows');
			// if (rows.length == editIndex + 1) {
			// 	objs.envVarDg.xdatagrid('appendRow', {taskId: taskId, status: 1, defaultVal: 0});
			// }
			rowCache[editIndex] = res.apiEnvVar;
			if ('undefined' != typeof rowCache.lastIndex && rowCache.lastIndex == editIndex) {
				objs.envVarDg.xdatagrid('appendRow', {taskId: taskId, status: 1, defaultVal: 0});
				rowCache.lastIndex = editIndex + 1;
			}
			$.xnotify(msg, {type: 'success'});
		} else {
			$.xnotify('系统错误！', {type: 'warning'});
		}
	}, 'json');
}

// 删除环境变量
function delRow(index, envId) {
	if (!envId) {
		objs.envVarDg.xdatagrid('deleteRow', index);
		return;
	}
	$.xconfirm({
		msg: '您确定删除该条环境变量配置吗?',
		okFn: function() {
			$.post(
				baseUrl + "/apiManager/envVarAction!delete.action",
				{
					'dto.apiEnvVar.envId': envId
				},
				function(data) {
					if (data == "success") {
						$.xalert({title:'提示',msg:'删除成功！'});
						objs.envVarDg.xdatagrid('reload');
					} else {
						$.xalert({title:'提示',msg:'系统错误！'});
					}
				}, "text");
		}
	});
}

// 监听输入框编辑
function onTextChange(newValue,oldValue) {
	if (newValue && newValue != oldValue) {
		saveEnvVar();
	}
}

// 监听checkbox编辑
function onCheckChange(checked) {
	if (checked) {
		var rows = objs.envVarDg.xdatagrid('getRows');
		rows = rows.map(function(v,i) {
			if (editIndex != i) {
				v.defaultVal = 0;
			}
		});
	} else {
		
	}
}